package com.blrs.service.dimlndustry.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.domain.DimIndustry;
import com.blrs.mapper.DimIndustryMapper;
import com.blrs.service.dimlndustry.IDimIndustryService;

@Service
public class DimIndustryServiceImpl implements IDimIndustryService {
    
    @Autowired
    private DimIndustryMapper dimIndustryMapper;

    @Override
    public List<DimIndustry> selectIndustryTree() {
        List<DimIndustry> allIndustries = dimIndustryMapper.selectIndustryList();
        
        if (allIndustries == null || allIndustries.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按父ID分组
        Map<String, List<DimIndustry>> parentIdMap = allIndustries.stream()
            .filter(industry -> industry != null)
            .collect(Collectors.groupingBy(industry -> 
                industry.getParentId() == null ? "" : industry.getParentId()));
        
        // 递归构建树形结构
        List<DimIndustry> rootNodes = parentIdMap.getOrDefault("", new ArrayList<>());
        rootNodes.forEach(node -> buildChildren(node, parentIdMap));
        
        return rootNodes;
    }

    @Override
    public DimIndustry selectIndustryById(String industryId) {
        return dimIndustryMapper.selectIndustryById(industryId);
    }

    private void buildChildren(DimIndustry node, Map<String, List<DimIndustry>> parentIdMap) {
        List<DimIndustry> children = parentIdMap.get(node.getIndustryId());
        if (children != null && !children.isEmpty()) {
            node.setChildren(children);
            // 递归处理每个子节点
            children.forEach(child -> buildChildren(child, parentIdMap));
        }
    }
} 